package com.dullfox.sbm.common.auth;

import com.dullfox.sbm.common.util.RedisUtil;
import com.dullfox.sbm.common.util.UUIDUtil;
import com.dullfox.sbm.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Author: zengdy
 * Date: 2018/10/30
 */
@Component
public class RedisTokenManager implements TokenManager {

    @Value("${token.timeout}")
    private int timeout;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 创建token
     */
    public String getToken(SysUser sysUser) {
        //使用uuid作为源token
        String token = UUIDUtil.generateUUID();
        redisUtil.set(token, sysUser, timeout);
        return token;
    }

    /**
     * 刷新用户
     */
    public void refreshUserToken(String token) {
        if (redisUtil.hasKey(token)) {
            redisUtil.expire(token, timeout);
        }
    }

    /**
     * 用户退出登陆
     */
    public void loginOff(String token) {
        redisUtil.del(token);
    }

    /**
     * 获取用户信息
     */
    public SysUser getUserByToken(String token) {
        if (redisUtil.hasKey(token)) {
            return (SysUser) redisUtil.get(token);
        }
        return null;
    }

}
